/**
 * Copyright 2018 人人开源 http://www.gbznt.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package io.gbznt.modules.sys.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.gbznt.common.constant.Variable;
import io.gbznt.common.utils.Constant;
import io.gbznt.common.utils.ShiroUtils;
import io.gbznt.modules.sys.dao.SysDeptDao;
import io.gbznt.modules.sys.entity.SysDeptEntity;
import io.gbznt.modules.sys.entity.SysUserEntity;
import io.gbznt.modules.sys.service.SysDeptService;
import io.gbznt.modules.sys.service.SysRoleDeptService;
import io.gbznt.modules.sys.service.SysUserRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jca.cci.object.SimpleRecordOperation;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.*;

@Service("sysDeptService")
public class SysDeptServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<SysDeptDao, SysDeptEntity>
		implements SysDeptService {
	@Autowired
	private SysDeptService sysDeptService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysRoleDeptService sysRoleDeptService;

	@Override
	public List<SysDeptEntity> queryList(@RequestParam Map<String, Object> params) {
		String status = (String) params.get("status");
		String isArea = (String) params.get("isArea");
		String type = (String) params.get("type");


		List<SysDeptEntity> deptList = this.list(new QueryWrapper<SysDeptEntity>()
			.eq(StringUtils.isNotBlank(status), "status", status)
			.eq(StringUtils.isNotBlank(type), "type", type)
			.in(!Constant.SUPER_ADMIN.equals(ShiroUtils.getUserId()),
					"id", this.getPermissionDeptIdsArr(true,true))
			.orderByAsc("order_num").orderByDesc("create_time")
		);

		for (SysDeptEntity sysDeptEntity : deptList) {
			SysDeptEntity parentDeptEntity = this.getById(sysDeptEntity.getParentId());
			if (parentDeptEntity != null) {
				sysDeptEntity.setParentName(parentDeptEntity.getName());
			}
			// 只能选择基地
			if(StringUtils.isNotEmpty(isArea) && 0==sysDeptEntity.getType()){
				sysDeptEntity.setNocheck(true);
			}

		}
		return deptList;
	}

	@Override
	public List<String> queryDetpIdList(String parentId) {
		return baseMapper.queryDetpIdList(parentId);
	}

	@Override
	public List<String> getSubDeptIdList(String deptId) {
		// 部门及子部门ID列表
		List<String> deptIdList = new ArrayList<>();

		// 获取子部门ID
		List<String> subIdList = queryDetpIdList(deptId);
		getDeptTreeList(subIdList, deptIdList);

		return deptIdList;
	}

	/**
	 * 递归
	 */
	private void getDeptTreeList(List<String> subIdList, List<String> deptIdList) {
		for (String deptId : subIdList) {
			List<String> list = queryDetpIdList(deptId);
			if (list.size() > 0) {
				getDeptTreeList(list, deptIdList);
			}

			deptIdList.add(deptId);
		}
	}

	@Override
	public List<SysDeptEntity> queryDetp(Integer value) {
		// TODO Auto-generated method stub
		return baseMapper.queryDetp(value);
	}

	@Override
	public SysDeptEntity getBySC(String sysCode, String companyId) {
		SysDeptEntity sysDeptEntity = this
				.getOne(new QueryWrapper<SysDeptEntity>().eq("sys_code", sysCode).eq("company_id", companyId));

		return sysDeptEntity;
	}

	@Override
	public SysDeptEntity selectByIdzdy(String id) {
		// TODO Auto-generated method stub
		SysDeptEntity sysdept = new SysDeptEntity();
		sysdept = baseMapper.sysdept(id);

		return sysdept;
	}

	/**
	 * 根据部门id查询出该部门的所有子部门
	 * 
	 * @param deptId
	 * @return
	 */
	@Override
	public String getDeptIds(String deptId) {
		String ids = deptId + ",";
		QueryWrapper<SysDeptEntity> ew = new QueryWrapper<SysDeptEntity>();
		ew.eq("PARENT_ID", deptId);
		List<SysDeptEntity> deptList = baseMapper.selectList(ew);
		if (deptList.size() < 1) {

		} else {
			for (SysDeptEntity sysDeptEntity : deptList) {
				ids += getDeptIds(sysDeptEntity.getId());
			}
		}
		return ids;
	}

	/**
	 * 根据部门id查询出该部门的所有子部门(返回String)
	 * 
	 * @param deptId
	 * @return
	 */
	@Override
	public String getDeptIdstuString(String deptId) {
		deptId = sysDeptService.getDeptIds(deptId);
		deptId = deptId.substring(0, deptId.length() - 1);
		return deptId;
	}

	/**
	 * 根据部门id查询出该部门的所有子部门(返回List)
	 * 
	 * @param dept
	 * @return
	 */
	@Override
    public List<SysDeptEntity> getDeptListByParentId(SysDeptEntity dept, List<SysDeptEntity> list) {
		list.add(dept);
		QueryWrapper<SysDeptEntity> ew = new QueryWrapper<SysDeptEntity>();
		ew.eq("PARENT_ID", dept.getId());
		List<SysDeptEntity> deptList = baseMapper.selectList(ew);
		if (deptList.size() < 1) {

		} else {
			for (SysDeptEntity sysDeptEntity : deptList) {	
				getDeptListByParentId(sysDeptEntity,list);
			}
		}
		return list;
	}

	@Override
	public String getDeptIdstuStringm(String deptId) {
		deptId = sysDeptService.getDeptIds(deptId);
		deptId = deptId.substring(0, deptId.length() - 1);
		String idsm="";
		String[]  strs=deptId.split(",");
		for(int i=0;i<strs.length;i++) {
			strs[i]="'"+strs[i]+"'";
			idsm+=strs[i]+",";
		}
		idsm=idsm.substring(0, idsm.length()-1);
		return idsm;
	}

	/**
	 * 获取有用权限的部门id
	 * @param hasSelf
	 * @param hasChild
	 * @return
	 */
	@Override
	public String getPermissionDeptIdsStr(Boolean hasSelf, Boolean hasChild) {
		SysUserEntity user = ShiroUtils.getUserEntity();

		//部门ID列表
		Set<String> deptIdList = new HashSet<>();

		//用户角色对应的部门ID列表
		List<String> roleIdList = sysUserRoleService.queryRoleIdList(user.getId());
		if(roleIdList.size() > 0){
			List<String> userDeptIdList = sysRoleDeptService.queryDeptIdList(roleIdList.toArray(new String[roleIdList.size()]));
			deptIdList.addAll(userDeptIdList);
		}

		if(hasSelf) {
			deptIdList.add(user.getDeptId());
			//用户子部门ID列表
			if (hasChild) {
				List<String> subDeptIdList = this.getSubDeptIdList(user.getDeptId());
				deptIdList.addAll(subDeptIdList);
			}
		}

		StringBuilder sqlFilter = new StringBuilder();

		if(deptIdList.size() > 0){
			sqlFilter.append("'").append(StringUtils.join(deptIdList, "','")).append("'");
		}

		return sqlFilter.toString();
	}

	/**
	 * 获取有用权限的部门id
	 * @param hasSelf
	 * @param hasChild
	 * @return
	 */
	@Override
	public List<String> getPermissionDeptIdsArr(Boolean hasSelf, Boolean hasChild) {
		SysUserEntity user = ShiroUtils.getUserEntity();

		//部门ID列表
		Set<String> deptIdList = new HashSet<>();

		//用户角色对应的部门ID列表
		List<String> roleIdList = sysUserRoleService.queryRoleIdList(user.getId());
		if(roleIdList.size() > 0){
			List<String> userDeptIdList = sysRoleDeptService.queryDeptIdList(roleIdList.toArray(new String[roleIdList.size()]));
			deptIdList.addAll(userDeptIdList);
		}

		if(hasSelf) {
			deptIdList.add(user.getDeptId());
			//用户子部门ID列表
			if (hasChild) {
				List<String> subDeptIdList = this.getSubDeptIdList(user.getDeptId());
				deptIdList.addAll(subDeptIdList);
			}
		}

		return new ArrayList<>(deptIdList);
	}

}
